package com.kkb.wx.contorller;

import com.alibaba.fastjson.JSONObject;
import com.kkb.controller.BaseController;
import com.kkb.domain.AjaxResult;
import com.kkb.pojo.TWxMember;
import com.kkb.utils.ServletUtils;
import com.kkb.wx.service.WxMemberService;
import com.kkb.wx.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.kkb.constant.GlobalConst.HEADER_AUTHORIZATION;

//微信会员控制层
@Controller
public class WxMemberController extends BaseController {
    @Autowired
    private WxMemberService wxMemberService;

    @PostMapping("member/login")
    @ResponseBody
    public AjaxResult login(@RequestBody HashMap<String, String> data) {
        try {
            logger.debug("data:"+data);
            String code = data.get("code");
            String encryptedData = data.get("encryptedData");
            String iv = data.get("iv");
            //使用微信工具类获取openId 和SessionKey
            JSONObject jsonObject = WxUtil.get(code);
            logger.debug("通过微信工具类获取openId 和SessionKey jsonObject:" + jsonObject);
            String openId = jsonObject.getString("openid");//openId 在后续作 为类似webjessionid来使用
            String session_key = jsonObject.getString("session_key");

            //调用service方法，完成登录与注册
            TWxMember member = wxMemberService.findByOpenId(openId);
            if (member == null) {
                //如果数据库中没有该用户数据（登录），需要解密数据并添加到数据库（注 册）
                // sessionKey解密用户数据，利用微信工具类
                JSONObject userInfo = WxUtil.getUserInfo(encryptedData, session_key, iv);
                logger.debug("解密出用户数据是userInfo："+userInfo);
                 member = new TWxMember();
                member.setCountry(userInfo.getString("country"));
                member.setNickName(userInfo.getString("nickName"));
                member.setAvatarUrl(userInfo.getString("avatarUrl"));
                member.setGender(userInfo.getString("gender"));
                member.setCity(userInfo.getString("city"));
                member.setProvince(userInfo.getString("province"));
                member.setCountry(userInfo.getString("country"));
                member.setLanguage(userInfo.getString("language"));
                member.setOpenId(userInfo.getString("openId"));
                member.setUnionId(userInfo.getString("unionId"));
                member.setCreateTime(new Date());
                logger.debug("调用Service 注册用户，用户数据是：" + member);
                //调用service实现注册
                wxMemberService.regWxMember(member);

            }
            Map<Object, Object> map = new HashMap<>();
            map.put("token", openId);
            map.put("userInfo", member);
            return AjaxResult.success(map);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error("请求失败：" + e.getMessage());
        }
    }


    //更新城市学科
    @PostMapping("member/setCityCourse")
    @ResponseBody
    public AjaxResult setCityCourse(@RequestBody HashMap<String ,String> data){
        try{logger.debug("data:{}",data);
            //从请求头获取Token 值
            HttpServletRequest request = ServletUtils.getRequest();
            String openId = request.getHeader(HEADER_AUTHORIZATION);
            data.put("openId",openId);
            //调用Service,传递Map(openId,cityID,subjectID),完成城市及学科的更新
            int result = wxMemberService.updateCityCourse(data);
            return toAjax(result);
        }catch(Exception e){
            logger.error("设置会员城市学科失败："+e.getMessage());
            return AjaxResult.error("更新失败");
        }
    }
}
